import sdk from '../core/index';
import rpg_component from "./rpg_component";
import { Icard } from "../core/tool/Icard";
import intent_component from "./intent_component";
import { analysisIntent } from "../core/tool/baseScene";
import common from "../core/tool/common";
import equip_component from "./equip_component";
import { quality, qualityName, 资源枚举, 道具枚举 } from "../shared/face/enums";
import { config, configKey } from "../config";
import follow_component from "./follow_component";
import talent_component from "./talent_component";
import { Item, UserLevel } from "../shared/face/index";
import { ItemType } from "../shared/face/enums";
import { Bag } from "../core/bag";
import MarketManage from "../core/manage/MarketManage";
import { mathType } from "../core/tool/face";
import { BagService } from "../service/BagService";

/**
 * 背包组件 - 现代化组件，使用依赖注入
 * 职责：
 * 1. 管理背包状态
 * 2. 处理用户交互
 * 3. 显示背包信息
 * 4. 通过注入的BagService处理业务逻辑
 */
import component, { ComType } from "../core/tool/component";
export default class bag_component extends component {
    private _bagService: BagService;
    private itemList: Item[] = [];
    private maxSize: number = 100;
    
    constructor() {
        super();
        // 使用依赖注入获取BagService（_开头，不会被持久化）
        this._bagService = this.getService<BagService>('BagService');
    }
    init() {
        this.itemList = [];
        console.log('背包组件初始化');

    }
    getEquipList(): Item[] {
        return this.itemList.filter((item) => item.type == ItemType.装备);
    }
    /**
     * 将背包Bag中的物品全部加入到itemList中
     */
    addBag(bag: Bag) {
        bag.items.forEach((item) => {
            this.addItem(item);
        });
    }
    /**
     * 使用物品
     * @param index 道具索引
     * @param count 使用数量
     */
    private async useItem(index: number, count: number) {
        const result = this._bagService.useItem(this.itemList, index, count);
        
        if (!result.success) {
            this.client_text(result.message);
            return;
        }
        
        // 更新背包状态
        this.itemList = result.newBagItems;
        
        // 根据动作类型处理不同的逻辑
        switch (result.actionType) {
            case 'equip':
                const equipCom = this.getComponent(ComType.装备栏) as equip_component;
                equipCom.addEquip(result.actionData);
                break;
            case 'resource':
                this.client_text(result.message);
                break;
            case 'consumable':
                // 调用消耗品使用逻辑
                const consumableResult = await this._bagService.useConsumable(result.usedItem,count, result.actionData.funcName, result.actionData.funcData, this.getBody());
                if (!consumableResult.success) {
                    // 退回背包
                    if (result.usedItem.stacking) {
                        // 可堆叠物品，添加一个带有数量的物品
                        let backItem = JSON.parse(JSON.stringify(result.usedItem));
                        backItem.count = result.count;
                        this.addItem(backItem);
                    } else {
                        // 不可堆叠物品，添加多个独立的物品
                        for (let i = 0; i < result.count; i++) {
                            let backItem = JSON.parse(JSON.stringify(result.usedItem));
                            backItem.count = 1;
                            this.addItem(backItem);
                        }
                    }
                    this.client_text(`消耗品使用失败: ${consumableResult.message},已退回背包`);
                }else{
                    if(consumableResult.message.length > 0){
                        this.client_text(consumableResult.message);
                    }
                }
                break;
            default:
                this.client_text(result.message);
                break;
        }
    }
    delItem(item: Item, count: number) {
        if (item.stacking) {
            // 可堆叠物品，减少数量
            let index = this.findIndex(item);
            if (index == -1) {
                console.error('道具不存在')
                return false;
            }
            let _item = this.itemList[index];
            _item.count -= count;
            if (_item.count <= 0) {
                this.itemList.splice(index, 1);
            }
        } else {
            // 不可堆叠物品，移除指定数量的独立物品
            let remainingCount = count;
            const itemsToRemove: number[] = [];
            
            // 找到所有匹配的物品
            for (let i = 0; i < this.itemList.length && remainingCount > 0; i++) {
                const bagItem = this.itemList[i];
                if (bagItem.id === item.id && bagItem.type === item.type) {
                    itemsToRemove.push(i);
                    remainingCount--;
                }
            }
            
            if (itemsToRemove.length < count) {
                console.error('道具数量不足')
                return false;
            }
            
            // 从后往前移除，避免索引变化
            for (let i = itemsToRemove.length - 1; i >= 0; i--) {
                this.itemList.splice(itemsToRemove[i], 1);
            }
        }
        return true;
    }
    findIndex(item: Item) {
        let idx = this.itemList.findIndex((v, i) => { return v.id == item.id && v.type == item.type })
        return idx;
    }
    /**
     * 背包主界面
     */
    client_main() {
        const card = sdk.tool.card.create();
        card.title('🎒我的背包');
        
        // 获取背包统计信息
        if (this.itemList.length == 0) {
            card.l('背包空空如也哦~');
        } else {
            let resList: string[] = [];
            let itemList: string[] = [];
            this.itemList.forEach((item, index) => {
                if (item.count == 0) {
                    return;
                }
                switch (item.type) {
                    case ItemType.装备:
                        const qualityText = Object.values(qualityName)[item.data.quality] || '未知';
                        itemList.push(`[${index + 1}]${item.emoji}${qualityText}·${item.name}`);
                        break;
                    case ItemType.资源:
                        resList.push(`${item.emoji} ${item.name}x${item.count}`);
                        break;
                    default:
                        itemList.push(`[${index + 1}]${item.emoji} ${item.name}x${item.count}`);
                        break;
                }

            });
            for (let i = 0; i < resList.length; i += 2) {
                let text = '';
                text += resList[i];
                if (i + 1 < resList.length) {
                    text += resList[i + 1];
                }
                card.l(text);
            }
            if (itemList.length > 0) {
                resList.length > 0 && card.title('📦我的物品');
                for (let i = 0; i < itemList.length; i++) {
                    card.l(itemList[i]);
                }
            }

        }
        if (this.itemList.length > 0) {
            // 使用配置化方式注册按钮意图
            this.registerBagButtonIntents(card);
        }
        this.client_text(card.getText());
        return card;
    }

    // 注册背包按钮意图的通用方法
    private registerBagButtonIntents(card: any): void {
        const buttonConfigs = [
            { text: '使用', action: 'client_useIndex', mathType: mathType.开头匹配 },
            { text: '整理', action: 'client_sort', mathType: mathType.完全匹配 },
            { text: '查看', action: 'client_look', mathType: mathType.开头匹配 },
            { text: '出售', action: 'client_sell', mathType: mathType.开头匹配 }
        ];

        this.registerButtonIntents(card, buttonConfigs);
    }
    /**
     * 订单预览 
     */
    order_look(data: { key: 资源枚举 | 道具枚举, val: number, type?: ItemType }[], mergeCard?: any) {
        let jude = true;
        if (mergeCard) {
            let card = sdk.tool.card.create();
            card.title('📋订单预览')
            data.forEach(item => {
                let _type = item.type ? item.type : configKey.资源表;
                const existingItem = this.itemList.find(i => i.id == item.key && i.type == _type);
                const _cfg = config.get(_type)?.get(item.key);
                if (existingItem) {
                    card.l(`${_cfg.emoji}${_cfg.name}x${item.val}(✅剩余${existingItem.count})`);
                } else {
                    jude = false;
                    card.l(`${_cfg.emoji}${_cfg.name}x${item.val}(🚫剩余0)`);
                }
            })
            mergeCard.merge(card);
        }
        return jude;
    }
    goldBuy(val: number) {
        return this.order_confirm([{ key: 资源枚举.金币, val: val }])
    }
    /**
     * 订单确认
     */
    order_confirm(data: { key: 资源枚举 | 道具枚举, val: number, type?: ItemType }[]): boolean {
        let card = sdk.tool.card.create();
        let list: string[] = [];
        let success = true;
        let change = false;
        data.forEach(item => {
            let _type = item.type ? item.type : configKey.资源表;
            const existingItem = this.itemList.find(i => i.id == item.key && i.type == _type);
            const _cfg = config.get(_type)?.get(item.key);
            if (item.val == 0) {
                list.push(`${_cfg.emoji}${_cfg.name}无变化`);
                return;
            }
            change = true;
            if (existingItem) {
                if (existingItem.count >= item.val) {
                    existingItem.count -= item.val;
                    list.push(`${_cfg.emoji}${_cfg.name}-${item.val}(剩余${existingItem.count})`);
                } else {
                    list.push(`🚫${_cfg.emoji}${_cfg.name}数量不足(你有${existingItem.count})`);
                    success = false;
                }
            } else {
                list.push(`🚫背包中没有${_cfg.emoji}${_cfg.name}`);
                success = false;
            }
        });
        if (this.getComponent(ComType.base).sys_leve == UserLevel.开发者) {
            this.client_text('🚫开发者模式 无视支付失败🚫');
            return true;
        }
        if (change) {
            card.title(`${success ? '✅' : '🚫'}支付${success ? '成功' : '失败'}`)
            for (let i = 0; i < list.length; i++) {
                card.l(list[i]);
            }
            this.client_text(card.getText());
        }

        return success;
    }
    client_sort(data: analysisIntent) {
        this.itemList = this._bagService.sortBag(this.itemList);
        this.client_text('背包整理完成');
        this.client_main();
    }
    client_useIndex(data: analysisIntent) {
        /**
         * 内容解析
         * 预期指令: 使用数字
         * 如使用0 使用1 使用2 使用3
         * 如使用0q1 使用1q2 使用2q3 使用3q4
         */
        let index_data = sdk.tool.common.cover_number(data.Message.content);
        if (!index_data.k1) {
            data.player.client_text('如使用0 使用1 使用2 使用3\n如使用0q1 使用1q2 使用2q3 使用3q4');
            return;
        }
        let item = this.itemList[index_data.k1 - 1];
        if (!item) {
            data.player.client_text('背包中没有该物品');
            return;
        }
        this.useItem(index_data.k1 - 1, index_data.k2 || 1);
    }
    client_sell(data: analysisIntent) {
        let index_data = sdk.tool.common.cover_number(data.Message.content);
        if (!index_data.k1) {
            this.client_text('道具出售:出售+ID');
            return;
        }
        let item = this.itemList[index_data.k1 - 1];
        if (!item) {
            this.client_text(`背包中没有ID:${index_data.k1}的物品`);
            return;
        }
        if (!index_data.k2) {
            index_data.k2 = 1;
        }
        // 取整
        index_data.k2 = Math.ceil(index_data.k2);
        if (index_data.k2 > item.count) {
            index_data.k2 = item.count;
        }
        
        let pop = this.getComponent(ComType.对话框) as any;
        pop._content = `请艾特我直接输入出售的单价`;
        pop.lisen((_data: analysisIntent) => {
            let price = sdk.tool.common.cover_number(_data.Message.content);
            if (!price.k1) {
                price.k1 = 1;
            }
            // 取整
            price.k1 = Math.ceil(price.k1);
            if (price.k1 > 1000000) {
                price.k1 = 1000000;
            }
            let card = sdk.tool.card.create();
            card.title('出售确认')
            card.l(`【[${index_data.k1}]${item.emoji}${item.name}】`);
            card.l(`数量:${index_data.k2}`);
            card.l(`单价:${price.k1}`);
            card.l(`总价:${index_data.k2 * price.k1}金币`);
            card.l(`如需修改单价可直接艾特我输入单价~`);
            const confirmButtonConfigs = [
                {
                    text: '确认',
                    mathType: mathType.完全匹配,
                    action: () => this.commitSell(index_data.k1 as number, index_data.k2 as number, price.k1 as number)
                },
                {
                    text: '取消',
                    mathType: mathType.完全匹配,
                    action: () => this.Pop_close()
                }
            ];
            pop.registerPopupButtonIntents(confirmButtonConfigs, this, card);
            this.client_text(card.getText());
        })
        pop.active();
    }
    commitSell(idx: number, count: number, price: number) {
        let item = this.itemList[idx - 1];
        if (!item) {
            this.client_text('背包中没有该物品');
            return;
        }
        let putItem = JSON.parse(JSON.stringify(item));
        putItem.count = count;
        MarketManage.put(putItem, this.id, price);
        this.delItem(item, count);
        this.client_text(`已将[${item.emoji}${item.name}]上架到交易所,单价:${price},交易情况将会通过[邮件]通知`);
        this.Pop_close();
    }
    client_look(data: analysisIntent) {
        let index_data = sdk.tool.common.cover_number(data.Message.content);
        if (!index_data.k1) {
            this.client_text('道具查看:查看+ID');
            return;
        }
        let item = this.itemList[index_data.k1 - 1];
        if (!item) {
            this.client_text('背包中没有该物品');
            return;
        }
        let card = sdk.prop.client_lookitemV2(item);
        this.client_img('panel_common',card.resData);
    }
    /**
     * 添加道具到背包
     * @param item 道具对象
     * @returns 是否成功
     */
    addItem(item: Item): boolean {
        // 检查背包是否已满
        if (this.itemList.length >= this.maxSize) {
            console.log('背包已满，无法添加道具');
            return false;
        }

        // 检查特殊物品（资源类）
        if (this.checkResourceItem(item)) {
            return true; // 资源类物品直接处理，不加入背包
        }

        // 查找是否已有相同道具
        const existingItem = this.findItem_id(item.id, item.type);
        if (existingItem && item.stacking) {
            // 合并相同道具
            existingItem.count += item.count;
            console.log(`道具 ${item.name} 数量增加 ${item.count}`);
            return true;
        }else{
            if(item.count > 1 && !item.stacking){
                let _item = JSON.parse(JSON.stringify(item));
                _item.count = 1;
                for(let i = 0; i < item.count; i++){
                    this.itemList.push(_item);
                }
            }else{
                this.itemList.push(item);
            }
        }
        // 添加新道具
        console.log(`添加道具: ${item.name} x${item.count}`);
        return true;
    }
    /**寻找指定道具 */
    findItem_id(id: string, type: string) {
        const existingItem = this.itemList.find(i => i.id == id && i.type == type);
        return existingItem;
    }
    // 检查道具是否为特殊物品  如经验
    private checkSpecialItem(item: Item) {
        let pass = false;
        switch (item.type) {
            case ItemType.资源:
                pass = this.checkResourceItem(item);
                break;
            // case ItemType.装备:
            // case ItemType.技能书:
            // case ItemType.宠物蛋:
            // case ItemType.血统卷轴:
            // case ItemType.盲盒:
            //     pass = false;
            //     break;
            default:
                pass = false;
                break;
        }
        return pass;
    }
    // 检查资源类特殊物品
    private checkResourceItem(item: Item) {
        let pass = true;
        switch (item.id) {
            case 资源枚举.经验:
                let rpgCom = this.getComponent(ComType.rpg) as rpg_component;
                rpgCom.addExp(item.count);
                break;
            case 资源枚举.血统经验:
                let talentCom = this.getComponent(ComType.血统) as talent_component;
                talentCom.addExp(item.count);
                break;
            default:
                pass = false;
                break;
        }
        return pass;
    }



    /**
     * 获取道具列表
     */
    getItemList(): Item[] {
        return this.itemList;
    }

    /**
     * 排序道具列表
     */
    sortItems(): void {
        const typeOrder = [
            ItemType.装备,
            ItemType.道具,
            ItemType.资源,
            ItemType.消耗品,        ];

        this.itemList.sort((a, b) => {
            const aIndex = typeOrder.indexOf(a.type);
            const bIndex = typeOrder.indexOf(b.type);
            return aIndex - bIndex;
        });

        console.log('道具列表已排序');
    }

    /**
     * 显示背包内容
     */
    showBag(): void {
        const card = sdk.tool.card.create();
        card.title('背包');
        card.l(`容量: ${this.itemList.length}/${this.maxSize}`);

        if (this.itemList.length === 0) {
            card.l('背包为空');
        } else {
            // 按类型分组显示
            const groupedItems = new Map<ItemType, Item[]>();

            for (const item of this.itemList) {
                if (!groupedItems.has(item.type)) {
                    groupedItems.set(item.type, []);
                }
                groupedItems.get(item.type)!.push(item);
            }

            for (const [type, items] of groupedItems) {
                card.l(`${type}:`);
                for (const item of items) {
                    card.l(`  ${item.emoji} ${item.name} x${item.count}`);
                }
            }
        }

        this.client_text(card.getText());
    }

    /**
     * 清理背包
     */
    clearBag(): void {
        this.itemList = [];
        console.log('背包已清空');
    }

    /**
     * 设置背包大小
     * @param size 新大小
     */
    setMaxSize(size: number): void {
        this.maxSize = size;
        console.log(`背包大小设置为: ${size}`);
    }

    /**
     * 获取背包大小
     */
    getMaxSize(): number {
        return this.maxSize;
    }

    /**
     * 获取背包使用率
     */
    getUsageRate(): number {
        return (this.itemList.length / this.maxSize) * 100;
    }


}
